package com.me.servlet;

import com.me.Utils.ServUtil;
import com.me.controllers.Controller;
import com.me.service.Services;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = {"/user/*", "/order/*", "/goods/*"})
public class GlobalServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf8");
		response.setCharacterEncoding("utf8");

		if (request.getMethod().toLowerCase().equals("post")) {
			ServUtil.parseParam(request);
		}

		String str = request.getRequestURI().substring(1);

		String[] reqs = str.split("/");//获取请求体

		String controllerName = reqs[0].substring(0, 1).toUpperCase() + reqs[0].substring(1) + "Controller";//获取Controller
		String tempState = reqs.length < 2 ? "index" : reqs[1];//获取请求
		Controller controller = null;

		String page = null;

		try {
			Services.addSingle(HttpServletRequest.class,request);
			Services.addSingle(HttpServletResponse.class,response);
			controller = (Controller) Services.resolve(Class.forName("com.me.controllers." + controllerName));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		String state = ServUtil.getRegState(tempState, ServUtil.getProperty("i_regex"));

		if (state != null && state != "") {
			controller.setRedirectParam();
			page = controller.excute(state, reqs.length > 2 ? reqs[2] : "");
		}

		page = page == null ? "/error.jsp" : page;

		if (page.equals("...")) {
			return;
		}

		if (page.startsWith(".")) {
			response.sendRedirect(page.substring(1));
		} else {
			request.getRequestDispatcher(page).forward(request, response);
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
			ServletException, IOException {
		doPost(request, response);
	}
}
